package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.Map;

/**
 * @Author: taku
 * @CreateTime: 2020-05-12 19:33
 * @Description: 自定义映射结果集
 */
public class MySerachResultMapper implements SearchResultMapper {
    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
        ArrayList<T> content = new ArrayList<>();
        //如果没有结果返回为空
        if (response.getHits() == null || response.getHits().getTotalHits() <= 0) {
            return new AggregatedPageImpl<T>(content);
        }

        SearchHits hits = response.getHits();
        SearchHit[] skuInfoArr= hits.getHits();
        for (SearchHit searchHit : skuInfoArr) {
            SkuInfo skuInfo = JSON.parseObject(searchHit.getSourceAsString(), SkuInfo.class);
            // 获取每一个hit对应的name的高亮信息
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("name");
            // 确定有高亮数据
            if (highlightField != null) {
                Text[] fragments = highlightField.getFragments();
                // 遍历高亮碎片
                StringBuffer sb = new StringBuffer();
                for (Text text : fragments) {
                    sb.append(text);
                }
                // 包skuInfo的name数据设置为高亮后的数据
                skuInfo.setName(sb.toString());
                content.add((T)skuInfo);
            }

        }


        // content, pageable, total, aggregations, scrollId
        return new AggregatedPageImpl<T>(content,pageable,response.getHits().getTotalHits(),response.getAggregations(),response.getScrollId());
    }
}
